package com.xbongbong.paas.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.productcategory.pojo.dto.ProductCategoryListDTO;
import com.xbongbong.pro.productcategory.pojo.vo.ProductCategoryListVO;
import com.xbongbong.saas.service.ProductCategoryService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/3/22 10:17
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/mobile/product/category")
public class MobileProductCategoryController {

    @Resource
    private ProductCategoryService productCategoryService;

    /**
     * 产品分类
     * @param productCategoryListDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid ProductCategoryListDTO productCategoryListDTO, BindingResult br) throws Exception {
        XbbResponse<ProductCategoryListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ProductCategoryListVO productCategoryListVO = productCategoryService.list(productCategoryListDTO);
                response = new XbbResponse<>(productCategoryListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
